﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using senlv.Models;
using static senlv.Models.RecommendHelper;
using static senlv.Models.RequestHelper;

namespace senlv.Controllers
{
    public class HomeController : Controller
    {
        public Token token;
        //读取appsettings.json中的token
        public HomeController(IOptions<Token> option)
        {
            token = option.Value;
        }
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult About()
        {
            ViewData["Message"] = "Your application description page.";

            return View();
        }
        public IActionResult Recommend()
        {
            ViewData["Message"] = "村落推荐系统";

            return View();
        }
        public IActionResult resume()
        {
            return View();
        }
        public IActionResult Recommend2()
        {
            ViewData["Message"] = "村落推荐系统";

            return View();
        }
        public IActionResult Recommend3()
        {
            ViewData["Message"] = "村落推荐系统";

            return View();
        }
    
        public IActionResult Contact()
        {
            ViewData["Message"] = "Your contact page.";

            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }
        public IActionResult VillageGuider()
        {
            return View();
        }
        public IActionResult VillageGuider2(int point)
        {
            string Name;
            switch (point)
            {
                case 0:
                    Name = "游客码头";
                    break;
                case 5:
                    Name = "游客中心";
                    break;
                case 7:
                    Name = "老周三村南门";
                    break;
                case 8:
                    Name = "民宿";
                    break;
                case 10:
                    Name = "老周三村东门";
                    break;
                case 12:
                    Name = "黎家乐";
                    break;
                case 13:
                    Name = "村史馆";
                    break;
                default:
                    Name = "自选地点";
                    break;
            }
            ViewData["name"] = Name;
            ViewData["point"] = point;
            
            return View();
        }
        public IActionResult Map(int starNum, double starLat, double starLng,int endNum, double endLat, double endLng)//,double x,double y,string endPoint
        {
            ViewData["starPoint"] = "{ lat:" + starLat + ",lng:" + starLng + "},";
            ViewData["endPoint"]  = "{ lat:" + endLat + ",lng:" + endLng + "},";
            string starPoint = "[{ lat:" + starLat + ",lng:" + starLng + "},";
            string endPoint = "{ lat:" + endLat + ",lng:" + endLng + "}]";
            string str = starPoint;
            MapHelper mapHelper = new MapHelper();
            mapHelper.FindWay(starNum);
            str += mapHelper.display(starNum, endNum);
            str += endPoint;
            ViewData["jsonStr"] = str;
           // Console.WriteLine("\npointList.jpoints[1].lat.ToString():");//+mapHelper.lineStr(mapName));距离存入记事本
            return View();
        }
        public static string GuidTo16String()
        {
            long i = 1;
            foreach (byte b in Guid.NewGuid().ToByteArray())
                i *= ((int)b + 1);
            return string.Format("{0:x}", i - DateTime.Now.Ticks);
        }
     
        [HttpGet]
        public IActionResult AIChat()
        {
            var webRequest = (HttpWebRequest)WebRequest.CreateHttp("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=yY42mD5rDYOkcZs8FrIiOnTb&client_secret=tNwottmO2CAnbPSXpT0GoxNPI72rzwql");
            webRequest.Method = "get";
            WebResponse response = webRequest.GetResponse();
            Stream resStream = response.GetResponseStream();
            string jsonString = "";
            using (StreamReader sr = new StreamReader(resStream))
            {
                jsonString = sr.ReadToEnd();
            }
            Baidu_API_json baidu = Newtonsoft.Json.JsonConvert.DeserializeObject<Baidu_API_json>(jsonString.ToString());
            //baidu.access_token;
            ViewData["Title"] = "AI小鹿 1.1";
            string _session = GuidTo16String();
            HttpContext.Session.SetString("session", _session);
            //登陆姓名存入Session
            //  ViewData["token"] = token.tokens;//读取appsettings.json中的token
            // Console.WriteLine(token.tokens);
            ViewData["token"] = baidu.access_token;
            return View();
        }
        [HttpGet]
        public IActionResult speechRecognition()
        {
            string _session = GuidTo16String();
            HttpContext.Session.SetString("session", _session);//登陆姓名存入Session
            ViewData["Title"] = "AI小鹿 1.1";
             return View();
        }
 
        [HttpPost]
        public IActionResult VillageRecommend([FromBody]recommend_json recommend_Json)
        {
            if (recommend_Json != null)
            {
                try
                {
                    pmmlPredictionResult predictionResult = new pmmlPredictionResult();
                    RecommendHelper recommend = new RecommendHelper();
                    predictionResult = recommend.pmmlPrediction(recommend_Json);
                    return Json(new { predictedValue = predictionResult.PredictedValue, predictedProbability0 = predictionResult.PredictedProbability0, predictedProbability1 = predictionResult.PredictedProbability1, predictedProbability2 = predictionResult.PredictedProbability2, predictedProbability3 = predictionResult.PredictedProbability3, predictedProbability4 = predictionResult.PredictedProbability4, predictedProbability5 = predictionResult.PredictedProbability5, predictedProbability6 = predictionResult.PredictedProbability6, });
                }
                catch(Exception ex)
                {
                    return Json(new { exception = ex.Message });
                }
             }
            return null;
        }
        [HttpPost]
        public IActionResult AsrData()
        {

            var files = Request.Form.Files;
            //var value = Request.Form.First(c => c.Key == "Name").Value;//获得表单文本项
            // hostingEnv.WebRootPath +
            string _session = HttpContext.Session.GetString("session");
            string fileName = _session + ".wav";
            fileName = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot") + $"\\{fileName}";
            foreach (var file in files)
            {

                using (FileStream fs = System.IO.File.Create(fileName))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }
            }

            var APP_ID = "15658497";
            var API_KEY = "yY42mD5rDYOkcZs8FrIiOnTb";
            var SECRET_KEY = "tNwottmO2CAnbPSXpT0GoxNPI72rzwql";
            var client = new Baidu.Aip.Speech.Asr(APP_ID, API_KEY, SECRET_KEY);
            //将model存在wwwroot中‘语音pcm文件地址’


            var data = System.IO.File.ReadAllBytes(fileName);
            client.Timeout = 120000; // 若语音较长，建议设置更大的超时时间. ms
            var result = client.Recognize(data, "wav", 16000);
            Console.Write(result);

            dynamic json = Newtonsoft.Json.Linq.JToken.Parse(result.ToString()) as dynamic;
            speech_output speech_Output = Newtonsoft.Json.JsonConvert.DeserializeObject<speech_output>(result.ToString());
            string str = speech_Output.result[0];
            return Json(new { result = str });
        }

        /// <summary>
        /// ChatAsync([FromBody]Model model)
        /// AIChat.cshtml中XMLHttpRequest.open()调用到的异步函数
        /// 生成json并post到阿里云AI接口，接收结果并处理返回json到前台
        /// </summary>
        /// <param name="model"></param>
        /// <returns>
        /// Json:{ result = context }
        /// 在前台用xhr.responseText接收
        /// </returns>
        [HttpPost]
        public async Task<IActionResult> ChatAsync([FromBody]Model model)
        {
            if (model != null)
            {
                string _session=HttpContext.Session.GetString("session");
                var parameters = new Dictionary<string, string>()
                {
                {"Action", "Chat"},
                {"InstanceId","chatbot-cn-4590ycpuy00023" },
                {"Utterance",model.input },
                {"SessionId",_session}
                };
                string domain = "chatbot.cn-shanghai.aliyuncs.com";
                var request = new RequestHelper(HttpMethod.Get, parameters);
                var url = request.GetUrl(domain);
               // Console.WriteLine(url);
                string result;
                using (var httpClient = new HttpClient())
                {
                    var response = await httpClient.GetAsync(url);
                    // response.EnsureSuccessStatusCode();
                    result = await response.Content.ReadAsStringAsync();
                    //使用Newtonsoft.Json
                   Console.WriteLine(result);//控制台打印返回的JSON
                    var jsonString = result;
                    dynamic json = Newtonsoft.Json.Linq.JToken.Parse(jsonString) as dynamic;
                    output output = Newtonsoft.Json.JsonConvert.DeserializeObject<output>(jsonString);
                    
                    // switch(output.Messages[0].Type)
                    string context="";
                    switch (output.Messages[0].Type)
                    {
                        case "Recommend":
                            context = "让我我猜猜，你是不是想问:<hr/>";
                            foreach (var item in output.Messages[0].Recommends)
                                context +=  "<a class=\"recommand\">"+item.Title+"</a><br/>";
                            return Json(new { result = context,type= "Recommend" });
                        case "Text":
                            if(output.Messages[0].Text.AnswerSource== "NO_ANSWER")
                                return Json(new { result = "亲，你说的这个小鹿还不是很懂哦，小鹿会请教工程师爸爸努力学会的!" });
                            context = output.Messages[0].Text.Content;
                            return Json(new { result = context });
                        case "Knowledge":
                            context = output.Messages[0].Knowledge.Title+"<hr/>"+ output.Messages[0].Knowledge.Content+"<hr/>"+output.Messages[0].Knowledge.Summary;
                            Console.WriteLine(context);
                            return Json(new { result = context,type = "Knowledge" });
                        default:
                            return Json(new { result = "小鹿系统出现了一些问题，请务必联系工程师电话：18250156433" });
                    }
                    //string context=json["Messages"]
                    // Console.WriteLine(context);
                }
            }
            else
            {
                return Json(new { result = "小鹿系统出现了一些问题，请务必联系工程师电话：18250156433<br/>汇报此BUG直接发15元微信红包" });
            }
        }
        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]

        public class Model
        {
            public string input { get; set; }
        }
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
        
        public IActionResult getToken()
        {
            var webRequest = (HttpWebRequest)WebRequest.CreateHttp("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=yY42mD5rDYOkcZs8FrIiOnTb&client_secret=tNwottmO2CAnbPSXpT0GoxNPI72rzwql");
            var jsonString = webRequest.GetResponse();
            Baidu_API_json baidu = Newtonsoft.Json.JsonConvert.DeserializeObject<Baidu_API_json>(jsonString.ToString());
            //baidu.access_token;
            return Json(new { result = "succeed"});//建議用XML解決呢，親
        }

    /// <summary>
    /// 以下类用于实例化收发json
    /// public class speech_output:用于Newtonsoft.Json接收语音识别API返回的JSON
    /// </summary>
        public class speech_output
    {
        public string corpus_no { get; set; } = "";
        public string err_msg { get; set; } = "";
        public string err_no { get; set; } = "";
        public List<string> result { get; set; } = new List<string>();
        public string sn { get; set; } = "";
    }
    public class output
        {
            public string SessionId { get; set; } = "";
            public List<Messages> Messages { get; set; } = new List<Messages>();
            public string MessageId { get; set; } = "";
            public string RequestId { get; set; } = "";
        }
        public class Messages
        {
            public Text Text { get; set; } = new Text();
            public string Type { get; set; } = "";
            public Knowledge Knowledge { get; set; } = new Knowledge();
            public List<Recommends> Recommends { get; set; } = new List<Recommends>();
        }
        public class Text
        {
            public string Content { get; set; } = "";
            public string AnswerSource { get; set; } = "";
        }
        public class Knowledge
        {
            public string Title { get; set; } = "";
            public string Content { get; set; } = "";
            public string Summary { get; set; } = "";
        }
        public class Recommends
        {
            public string Title { get; set; } = "";
            public string KnowledgeId { get; set; } = "";
            public string AnswerSource { get; set; } = "";
        }


    public class Baidu_API_json
    {
     public string refresh_token { get;set;}="";
     public int expires_in { get;set;}
     public string session_key { get;set;}="";
     public string access_token { get;set;}="";
     public string scope { get;set;}="";
     public string session_secret { get;set;}="";
    }
        public class recommend_json
        {
            public string b { get; set; } = "";
            public string c { get; set; } = "";
            public string d { get; set; } = "";
            public string e { get; set; } = "";
            public string f { get; set; } = "";
            public string g { get; set; } = "";
            public string h { get; set; } = "";
         public string i { get; set; } = "";
     public string j { get; set; } = "";
     public string k { get; set; } = "";
     public string l { get; set; } = "";
     public string m { get; set; } = "";
     public string  n{ get; set; } = "";
     public string o { get; set; } = "";
     public string p { get; set; } = "";
     public string q { get; set; } = "";
     public string r { get; set; } = "";
     public string s { get; set; } = "";
     public string t { get; set; } = "";
            public string u { get; set; } = "";
        }

    }
}
